package com.eastfair.venueservice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.echo.core.EchoService;
import com.eastfair.home.dto.ReportServiceAuditDTO;
import com.eastfair.venueservice.dto.*;
import com.eastfair.venueservice.entity.ServiceBooking;
import com.eastfair.venueservice.service.ServiceBookingService;
import com.eastfair.venueservice.vo.ServiceBookingStatisticsVO;
import com.eastfair.venueservice.vo.ServiceBookingVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 服务预订项
 * </p>
 *
 * @author linan
 * @date 2022-08-05
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/serviceBooking")
@Api(value = "ServiceBooking", tags = "服务预订项")
@PreAuth(replace = "venueservice:serviceBooking:")
public class ServiceBookingController extends SuperController<ServiceBookingService, Long, ServiceBooking, ServiceBookingPageQuery, ServiceBookingSaveDTO, ServiceBookingUpdateDTO> {

    @Autowired
    private EchoService echoService;

    @Override
    public void handlerResult(IPage<ServiceBooking> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<ServiceBooking> serviceBookingList = list
                .stream()
                .map((map) -> ServiceBooking.builder().build())
                .collect(Collectors.toList());
        return R.success(baseService.saveBatch(serviceBookingList));
    }

    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ServiceBookingPageQuery> params) {
        ServiceBookingPageQuery pageQuery = params.getModel();
        //分页处理
        if(ContextUtil.getProjectId()!=null){
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 查询展位上预定的服务列表.
     *
     * @param serviceBookingDTO the service booking dto
     * @return the r
     */
    @PostMapping("/site/query")
    public R<List<ServiceBookingVO>> queryBySiteName(@RequestBody ServiceBookingDTO serviceBookingDTO) {
        log.info("queryBySiteName - 查询展位上预定的服务列表, serviceBookingDTO= {}", serviceBookingDTO);
        return R.successDef(baseService.listServiceBookingBySiteName(serviceBookingDTO));
    }

    /**
     * 添加服务预订
     * @param serviceBookingDTO serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "添加服务预订")
    @SysLog("添加服务预订")
    @PostMapping(value = "/addServiceBooking")
    public R<Boolean> addServiceBooking(@RequestBody @Validated @NotEmpty List<ServiceBookingDTO> serviceBookingDTO){
        try {
            return R.success(baseService.addServiceBooking(serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 添加订单服务预订
     * @param serviceBookingDTO serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "添加订单服务预订")
    @SysLog("添加订单服务预订")
    @PostMapping(value = "/addServiceBookingOfOrder")
    public R<Boolean> addServiceBookingOfOrder(@RequestBody @Validated @NotEmpty List<ServiceBookingDTO> serviceBookingDTO){
        try {
            return R.success(baseService.addServiceBookingOfOrder(serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 添加服务预订（报馆后预订的服务）
     * @param serviceBookingDTO serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "添加服务预订（报馆后预订的服务）")
    @SysLog("添加订单服务预订")
    @PostMapping(value = "/addServiceBookingAfterReport")
    public R<Boolean> addServiceBookingAfterReport(@RequestBody @Validated @NotEmpty List<ServiceBookingDTO> serviceBookingDTO){
        try {
            return R.success(baseService.addServiceBookingAfterReport(serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 保存服务预订
     * @param serviceBookingDTO serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "保存服务预订")
    @SysLog("添加订单服务预订")
    @PostMapping(value = "/saveServiceBooking")
    public R<Boolean> saveServiceBooking(@RequestBody @Validated @NotEmpty List<ServiceBookingDTO> serviceBookingDTO){
        try {
            return R.success(baseService.saveServiceBooking(serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 删除预定服务
     * @param serviceBookingDTO serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "删除预定服务")
    @SysLog("删除预定服务")
    @PostMapping(value = "/delServiceBooking")
    public R<Boolean> delServiceBooking(@RequestBody ServiceBookingDTO serviceBookingDTO){
        try {
            return R.success(baseService.removeByIdsOfLogic(ConvertUtil.convertList(Collections.singletonList(serviceBookingDTO), ServiceBooking.class)));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 服务预订列表
     *
     * @param serviceBookingQuery 服务预订列表
     * @return R
     */
    @ApiOperation(value = "服务预订列表", notes = "服务预订列表")
    @PostMapping("/queryServiceBookingList")
    public R<List<ServiceBookingVO>> queryServiceBookingList(@RequestBody ServiceBookingQuery serviceBookingQuery) {
        log.info("queryServiceBookingList - 服务预订列表 serviceBookingQuery={}", serviceBookingQuery);
        return R.success(baseService.queryServiceBookingList(serviceBookingQuery));
    }

    /**
     * 订单服务预订列表
     *
     * @param serviceBookingQuery 订单服务预订列表
     * @return R
     */
    @ApiOperation(value = "订单服务预订列表", notes = "订单服务预订列表")
    @PostMapping("/queryServiceBookingListOfOrder")
    public R<List<ServiceBookingVO>> queryServiceBookingListOfOrder(@RequestBody ServiceBookingQuery serviceBookingQuery) {
        log.info("queryServiceBookingListOfOrder - 服务预订列表 serviceBookingQuery={}", serviceBookingQuery);
        return R.success(baseService.queryServiceBookingListOfOrder(serviceBookingQuery));
    }

    /**
     * 回填预订服务的审核结果
     * @param serviceBookingDTO serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "回填预订服务的审核结果")
    @PostMapping(value = "/updateServiceBookingAuditResult")
    public R<Boolean> updateServiceBookingAuditResult(@RequestBody List<ServiceBookingDTO> serviceBookingDTO){
        try {
            return R.success(baseService.updateServiceBookingAuditResult(serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 报馆提交服务预订
     * @param reportSpaceId 报馆ID
     * @param reportSpaceAuditId 报馆审核ID
     * @return R<Boolean>
     */
    @ApiOperation(value = "报馆提交服务预订")
    @GetMapping(value = "/submitServiceBookingWhenReport")
    public R<List<ReportServiceAuditDTO> > submitServiceBookingWhenReport(@RequestParam("reportSpaceId") Long reportSpaceId, @RequestParam("reportSpaceAuditId") Long reportSpaceAuditId) {
        try {
            return R.success(baseService.submitServiceBookingWhenReport(reportSpaceId,reportSpaceAuditId));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 报馆取消服务预订
     * @param reportSpaceId 报馆ID
     * @return R<Boolean>
     */
    @ApiOperation(value = "报馆取消服务预订")
    @GetMapping(value = "/cancelBookingOfReportSpace")
    public R<Boolean> cancelBookingOfReportSpace(@RequestParam("reportSpaceId") Long reportSpaceId) {
        try {
            return R.success(baseService.cancelBookingOfReportSpace(reportSpaceId));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 服务预订管理列表
     *
     * @param serviceBookingQuery 服务预订管理列表
     * @return R
     */
    @ApiOperation(value = "服务预订管理列表", notes = "服务预订管理列表")
    @PostMapping("/queryServiceBookingManage")
    public R<Page<ServiceBookingVO>> queryServiceBookingManage(@RequestBody PageParams<ServiceBookingQuery> serviceBookingQuery) {
        log.info("queryServiceBookingManage - 服务预订管理列表 queryServiceBookingList={}", serviceBookingQuery);
        return R.success(baseService.queryServiceBookingManage(serviceBookingQuery));
    }

    /**
     * 主场一键报馆的全部服务
     *
     * @param serviceBookingQuery 主场一键报馆的全部服务
     * @return R
     */
    @ApiOperation(value = "主场一键报馆的全部服务", notes = "主场一键报馆的全部服务")
    @PostMapping("/queryServiceBookingOfHome")
    public R<Page<ServiceBookingVO>> queryServiceBookingOfHome(@RequestBody PageParams<ServiceBookingQuery> serviceBookingQuery) {
        log.info("queryServiceBookingOfHome - 主场一键报馆的全部服务 serviceBookingQuery={}", serviceBookingQuery);
        return R.success(baseService.queryServiceBookingOfHome(serviceBookingQuery));
    }

    /**
     * 报馆服务列表
     * @param serviceBookingQuery
     * @return R
     */
    @ApiOperation(value = "报馆服务列表", notes = "报馆服务列表")
    @PostMapping("/queryReportSpaceService")
    public R<Page<ServiceBookingVO>> queryReportSpaceService(@RequestBody PageParams<ServiceBookingQuery> serviceBookingQuery) {
        log.info("queryReportSpaceService - 报馆服务列表 serviceBookingQuery={}", serviceBookingQuery);
        return R.success(baseService.queryReportSpaceService(serviceBookingQuery));
    }

    /**
     * 取消预订
     * @param serviceBookingUpdateDTO 预订服务
     * @return R<Boolean>
     */
    @ApiOperation(value = "取消预订")
    @SysLog("取消预定服务")
    @PostMapping("/cancelServiceBooking")
    public R<Boolean> cancelServiceBooking(@RequestBody @Validated(SuperEntity.Update.class) ServiceBookingUpdateDTO serviceBookingUpdateDTO) {
        try {
            return R.success(baseService.updateById(ServiceBooking.builder()
                    .id(serviceBookingUpdateDTO.getId())
                    .isEnabled(BusinessConstant.NO).build()));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 主场一键报馆服务
     * @param serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "主场一键报馆服务")
    @PostMapping(value = "/submitServiceBookingToVenue")
    public R<Boolean> submitServiceBookingToVenue(@RequestBody List<ServiceBookingDTO> serviceBookingDTO) {
        log.info("submitServiceBookingToVenue - 主场一键报馆服务 serviceBookingDTO={}", serviceBookingDTO);
        try {
            return R.success(baseService.submitServiceBookingToVenue(serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 主场一键报馆服务（客展导入）
     * @param serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "主场一键报馆服务（客展导入）")
    @PostMapping(value = "/submitServiceBookingToVenueOfImport")
    public R<Boolean> submitServiceBookingToVenueOfImport(@RequestBody List<ServiceBookingDTO> serviceBookingDTO) {
        log.info("submitServiceBookingToVenueOfImport - 主场一键报馆服务（客展导入） serviceBookingDTO={}", serviceBookingDTO);
        try {
            return R.success(baseService.submitServiceBookingToVenueOfImport(serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 查询报馆服务数量
     * @param reportVenueSpaceNumbers
     * @return R<Boolean>
     */
    @ApiOperation(value = "查询报馆服务数量")
    @PostMapping(value = "/queryBookingServiceNum")
    public R<Map<String,Integer>> queryBookingServiceNum(@RequestBody List<String> reportVenueSpaceNumbers) {
        log.info("submitServiceBookingToVenue - 查询报馆服务数量 reportVenueSpaceNumbers={}", reportVenueSpaceNumbers);
        try {
            return R.success(baseService.queryBookingServiceNum(reportVenueSpaceNumbers));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 修改订单下服务提交状态
     * @param serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "修改订单下服务提交状态")
    @PostMapping(value = "/updateBookingServiceOrderStatus")
    public R<Boolean> updateBookingServiceOrderStatus(@RequestBody ServiceBookingDTO serviceBookingDTO) {
        log.info("updateBookingServiceOrderStatus - 修改订单下服务提交状态 serviceBookingDTO={}", serviceBookingDTO);
        try {
            return R.success(baseService.updateBookingServiceOrderStatus(null, serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 统计展厅报馆服务数量
     *
     * @param serviceBookingQuery 统计展厅报馆服务数量
     * @return R
     */
    @ApiOperation(value = "统计展厅报馆服务数量", notes = "统计展厅报馆服务数量")
    @PostMapping("/queryReportServiceCount")
    public R<List<ServiceBookingVO>> queryReportServiceCount(@RequestBody ServiceBookingQuery serviceBookingQuery) {
        log.info("queryReportServiceCount - 统计展厅报馆服务数量 serviceBookingQuery={}", serviceBookingQuery);
        return R.success(baseService.queryReportServiceCount(serviceBookingQuery));
    }

    /**
     * 导出展位预定的服务列表.
     *
     * @param serviceBookingDTO the service booking dto
     * @param response          the response
     * @throws Exception the exception
     */
    @PostMapping("/site/export")
    public void exportBySiteName(@RequestBody ServiceBookingDTO serviceBookingDTO, HttpServletResponse response) throws Exception {
        log.info("exportBySiteName - 导出展位预定的服务列表, serviceBookingDTO={}", serviceBookingDTO);
        baseService.exportServiceBookingBySiteName(serviceBookingDTO, response);
    }

    /**
     * 报馆核定导入.
     *
     * @param file the multipart file
     * @return the r
     * @throws Exception the exception
     */
    @PostMapping("/import/for/report/check")
    public R<Boolean> importForReportCheck(@RequestBody MultipartFile file) throws Exception {
        log.info("importForReportCheck - 报馆核定导入");
        List<ServiceBookingDTO> serviceBookingList = baseService.importForReportCheck(file);
        return R.successDef(baseService.updateReportCheckStatus(serviceBookingList));
    }

    /**
     * 统计服务预定排行.
     *
     * @param exhibitionManageId the exhibition manage id
     * @param homeId             the home id
     * @param topN               the top n
     * @return the r
     */
    @GetMapping("/count/service/book/num")
    public R<List<Map<String, Object>>> countHomeServiceBookingNum(@RequestParam("exhibitionManageId") Long exhibitionManageId,
                                                                   @RequestParam("homeId") Long homeId,
                                                                   @RequestParam("topN") Integer topN) {
        log.info("countHomeServiceBookingNum - 统计服务预定排行, exhibitionManageId={}, homeId={}, topN={}", exhibitionManageId, homeId, topN);
        return R.successDef(baseService.countHomeServiceBookingNum(exhibitionManageId, homeId, topN));
    }

    /**
     * 统计服务已销售排行.
     *
     * @param exhibitionManageId the exhibition manage id
     * @param homeId             the home id
     * @param topN               the top n
     * @return the r
     */
    @GetMapping("/count/payed/service/book/num")
    public R<List<Map<String, Object>>> countHomeHasPayServiceBookingNum(@RequestParam("exhibitionManageId") Long exhibitionManageId,
                                                                   @RequestParam("homeId") Long homeId,
                                                                   @RequestParam("topN") Integer topN) {
        log.info("countHomeHasPayServiceBookingNum - 统计服务已销售排行, exhibitionManageId={}, homeId={}, topN={}", exhibitionManageId, homeId, topN);
        return R.successDef(baseService.countHomeHasPayServiceBookingNum(exhibitionManageId, homeId, topN));
    }

    /**
     * 统计展会报馆进度.
     *
     * @param serviceBookingQuery the service booking query
     * @return the r
     */
    @PostMapping("/count/reportService/process")
    public R<List<ServiceBookingVO>> countReportServiceProcess(@RequestBody ServiceBookingQuery serviceBookingQuery) {
        log.info("countReportServiceProcess - 统计展会报馆进度, serviceBookingQuery={}", serviceBookingQuery);
        return R.successDef(baseService.countReportServiceProcess(serviceBookingQuery));
    }

    /**
     * 主场服务派工
     * @param serviceBookingDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "主场服务派工")
    @PostMapping(value = "/submitServiceBookingToDispatch")
    public R<Boolean> submitServiceBookingToDispatch(@RequestBody List<ServiceBookingDTO> serviceBookingDTO) {
        log.info("submitServiceBookingToDispatch - 主场服务派工 serviceBookingDTO={}", serviceBookingDTO);
        try {
            return R.success(baseService.submitServiceBookingToDispatch(serviceBookingDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }
    /**
     * 更新库存
     * @param serviceOrderDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "更新库存")
    @PostMapping(value = "/updateServiceInventory")
    public R<Boolean>  updateServiceInventory(@RequestBody ServiceOrderDTO serviceOrderDTO){
        try {
            return R.success(baseService.updateServiceInventory(serviceOrderDTO));
        } catch(BizException biz) {
            return R.fail(biz);
        }
    }


    /**
     * 主办已预定的服务统计
     * @param serviceBookingQuery
     * @return R
     */
    @ApiOperation(value = "主办已预定的服务统计", notes = "主办已预定的服务统计")
    @PostMapping("/querySponsorServiceBookingStat")
    public R<ServiceBookingStatisticsVO> querySponsorServiceBookingStat(@RequestBody ServiceBookingQuery serviceBookingQuery) {
        log.info("querySponsorServiceBookingStat - 主办已预定的服务统计 serviceBookingQuery={}", serviceBookingQuery);
        return R.success(baseService.querySponsorServiceBookingStat(serviceBookingQuery));
    }
}
